/*
 * Copyright 2020-2030 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.gitee.minimalismstyle.fresh.oss.store.impl

import com.gitee.minimalismstyle.fresh.common.core.extra.log
import com.gitee.minimalismstyle.fresh.oss.api.model.OssFile
import com.gitee.minimalismstyle.fresh.oss.config.OssProperties
import com.gitee.minimalismstyle.fresh.oss.store.Store
import org.apache.commons.lang3.time.DateFormatUtils
import org.apache.commons.net.ftp.FTPClient
import org.springframework.stereotype.Service
import java.io.IOException
import java.io.InputStream
import java.io.OutputStream
import java.util.*

/**
 * ftp存储文件，不支持分布式
 * @author maoxiaodong
 */
@Service
class FtpStore(val ossProperties: OssProperties) : Store {

    override fun write(ossFile: OssFile, inputStream: InputStream): String {
        val uuid = UUID.randomUUID().toString()
        val dateString = DateFormatUtils.format(Date(), "yyyy/MM/dd")// 将文件按照年月日分开
        var ftpClient: FTPClient? = null
        val directory = "${ossProperties.ftp.rootPath}/${dateString}"
        val fileName = "${uuid}.${ossFile.extName}"
        val path = "${directory}/${fileName}"
        try {
            ftpClient = login()
            changeWorkingDirectory(ftpClient, directory)
            ftpClient.storeFile(path, inputStream)
            ftpClient.logout()
        } catch (e: IOException) {
            log.error("FTP操作异常", e)
            throw RuntimeException(e)
        } finally {
            if (ftpClient != null) {
                if (ftpClient.isConnected) {
                    try {
                        ftpClient.disconnect()
                    } catch (ioe: IOException) {
                        log.error("关闭FTP连接异常")
                    }
                }
            }
        }
        return path
    }

    override fun read(ossFile: OssFile, os: OutputStream) {
        var ftpClient: FTPClient? = null
        try {
            ftpClient = login()
            ftpClient.retrieveFile(ossFile.path, os)
            ftpClient.logout()
        } catch (e: IOException) {
            log.error("FTP操作异常", e)
            throw RuntimeException(e)
        } finally {
            if (ftpClient != null) {
                if (ftpClient.isConnected) {
                    try {
                        ftpClient.disconnect()
                    } catch (ioe: IOException) {
                        log.error("关闭FTP连接异常")
                    }
                }
            }
        }
    }

    override fun read(ossFile: OssFile): InputStream {
        var ftpClient: FTPClient? = null
        var data: ByteArray = byteArrayOf()
        try {
            ftpClient = login()
            ftpClient.storeFileStream(ossFile.path).use {
                it.write(data)
            }
            ftpClient.logout()
        } catch (e: IOException) {
            log.error("FTP操作异常", e)
            throw RuntimeException(e)
        } finally {
            if (ftpClient != null) {
                if (ftpClient.isConnected) {
                    try {
                        ftpClient.disconnect()
                    } catch (ioe: IOException) {
                        log.error("关闭FTP连接异常")
                    }
                }
            }
        }
        return data.inputStream()
    }

    override fun delete(path: String) {
        var ftpClient: FTPClient? = null
        try {
            ftpClient = login()
            ftpClient.deleteFile(path)
            ftpClient.logout()
        } catch (e: IOException) {
            log.error("FTP操作异常", e)
            throw RuntimeException(e)
        } finally {
            if (ftpClient != null) {
                if (ftpClient.isConnected) {
                    try {
                        ftpClient.disconnect()
                    } catch (ioe: IOException) {
                        log.error("关闭FTP连接异常")
                    }
                }
            }
        }
    }

    /**
     * 登录ftp
     */
    private fun login(): FTPClient{
        val ftpClient = FTPClient()
        ftpClient.connect(ossProperties.ftp.host, ossProperties.ftp.port)
        ftpClient.login(ossProperties.ftp.username, ossProperties.ftp.password)
        if (ossProperties.ftp.mode.equals("passive", ignoreCase = true)) { //被动模式:passive
            ftpClient.enterLocalPassiveMode()
        } else { //主动模式:active
            ftpClient.enterLocalActiveMode()
        }
        ftpClient.controlEncoding = ossProperties.ftp.controlEncoding
        ftpClient.setFileType(ossProperties.ftp.fileType)
        return ftpClient
    }

    private fun changeWorkingDirectory(ftpClient: FTPClient, directory: String){
        val directoryList = directory.split("/")
        var path = ""
        directoryList.forEach {
            path = "$path/$it"
            val changeWorkingDirectoryResult = ftpClient.changeWorkingDirectory(path)
            if(!changeWorkingDirectoryResult){
                ftpClient.makeDirectory(it)
                ftpClient.changeWorkingDirectory(path)
            }
        }
    }
}